﻿using BrnMall.Sdk.WeiXin;
using Core.Configuration.Config;
using Core.Sdk.WeiXin.Domain.pay;
using Core.Sdk.WeiXin.Tool;
using IconYuan.Manager.Orders;
using IconYuan.Manager.Pays;
using IconYuan.Manager.Users;
using IconYuan.Model.Entity.Orders;
using IconYuan.Model.Entity.Pays;

namespace IconYuan.Api.Services
{
    public class PayServices
    {
        /// <summary>
        /// 订单分账
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public static async Task<string> Profit(Order order)
        {
            var errMsg = string.Empty;
            var paymentSvc = new PayManager();
            var orderSvc = new OrderManager();
            if (order.is_settled == 1) return string.Empty;
            var payment = await paymentSvc.GetAsync(x => x.store_id == order.store_id);
            var payInput = ToPayInput(payment);
            try
            {
                //添加分账人
                var receivers = await AddReceiver(order, payInput);
                //分账接口
                var res = PaySdk.ProfitSharing(payInput, order.transaction_id.Trim(), order.order_no.Trim(), receivers);
                errMsg = res.IsSuccess() ? "" : res.GetErrMsg();
            }
            catch (Exception ex)
            {
                errMsg = ex.ToString();
            }

            var is_settled = 1;
            if (errMsg.Contains("未找到订单的佣金记录") || errMsg.Contains("可分账金额不足"))
            {
                is_settled = 2;
                PaySdk.FinishProfit(payInput, order.transaction_id.Trim(), order.order_no.Trim());
            }
            if (errMsg.Contains("可分账金额不足"))
                errMsg = $"未返佣,不能重复分账:{errMsg}";

            //更新分账状态
            if (order.is_settled != 1)
                await orderSvc.UpdateAsync(x => new Order() { is_settled = is_settled }, y => y.order_id == order.order_id);
            return errMsg;
        }

        /// <summary>
        /// 添加分账人
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public static async Task<List<SharingReceiver>> AddReceiver(Order order, PayInput payInput)
        {
            var oauthSvc = new OauthManager();
            var balanceLogSvc = new BalanceLogManager();
            var balanceLog = await balanceLogSvc.GetAsync(x => x.scene == 60 && x.amount > 0 && x.order_id == order.order_id);
            if (balanceLog == null) throw new Exception("未找到订单的佣金记录");
            //分佣人
            var oauth = await oauthSvc.GetAsync(x => x.user_id == balanceLog.user_id);
            //分佣金额 单位:分
            var amount = (int) (balanceLog.amount * 100);
            if (amount < 1) return new List<SharingReceiver>();

            var receive = new SharingReceiver(amount, oauth.open_id, string.Empty, balanceLog.describe);
            var result = PaySdk.AddReceiver(payInput, receive);
            if (!result.IsSuccess())
                throw new Exception(result.GetErrMsg());   //添加分账人失败

            return new List<SharingReceiver> { receive };
        }
        /// <summary>
        /// 结束分账
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public static async Task<string> FinishProfit(Order order)
        {
            var paymentSvc = new PayManager();
            try
            {
                var payment = await paymentSvc.GetAsync(x => x.store_id == order.store_id);
                var payInput = ToPayInput(payment);
                PaySdk.FinishProfit(payInput, order.transaction_id.Trim(), order.order_no.Trim());
            }
            catch
            {

            }
            return string.Empty;
        }

        private static PayInput ToPayInput(Payment payment)
        {
            return new PayInput()
            {
                AppId = payment.appid,
                MchId = payment.mchid,
                MchKey = payment.mchkey,
                CertPath = $"{GlobalConfig.BaseDirectory}/{payment.cert_pem}",
                profit = 1,
            };
        }
       
    }
}
